package com.gitee.apecome.core.remote;

import com.gitee.apecome.core.remote.bean.ApeRpcRequest;
import com.gitee.apecome.core.remote.bean.ApeRpcResponse;
import com.gitee.apecome.core.remote.net.netty.client.Client;
import com.gitee.apecome.core.remote.net.netty.client.NettyConnectClient;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class ApeRpcFactory {

    private static volatile ApeRpcFactory instance = new ApeRpcFactory();

    public static ApeRpcFactory newInstance() {
        return instance;
    }

    // future respinse 数据集
    private Map<String, ApeRpcFutureResponse> futureResponsePool = new ConcurrentHashMap<>();

    private Map<String, Client> clientPool = new ConcurrentHashMap<>();

    public void setClient(String host, Integer port, Client client) {
        clientPool.put(getClientKey(host, port), client);
    }

    private String getClientKey(String host, Integer port) {
        return host + "#" + port.toString();
    }

    public Client getConnection(String host, Integer port) {
        Client client = clientPool.get(getClientKey(host, port));
        if (Objects.isNull(client)) {
            synchronized (this) {
                Client clientSecond = clientPool.get(getClientKey(host, port));
                if (Objects.isNull(clientSecond)) {
                    setClient(host, port, NettyConnectClient.newInstance(host, port));
                }
            }
        }
        return clientPool.get(getClientKey(host, port));
    }

    public void setFutureResponse(String requestId, ApeRpcFutureResponse futureResponse) {
        futureResponsePool.put(requestId, futureResponse);
    }


    public void removeFuture(String requestId) {
        futureResponsePool.remove(requestId);
    }


    public void setResponse(ApeRpcResponse apeRpcResponse) {
        ApeRpcFutureResponse futureResponse = futureResponsePool.get(apeRpcResponse.getRequestId());
        futureResponse.setResponse(apeRpcResponse);
    }
}
